package com.workingpub.commons.jdbc.builder.ognl;

import java.util.HashMap;
import java.util.Map;

import com.workingpub.commons.utils.io.ResourceUtil;

import ognl.ClassResolver;

/**
 * Custom ognl {@code ClassResolver} which behaves same like ognl's
 * {@code DefaultClassResolver}. But uses the {@code Resources} utility class to
 * find the target class instead of {@code Class#forName(String)}.
 * 
 * @author taoping
 *
 */
public class OgnlClassResolver implements ClassResolver {
	private Map<String, Class<?>> classes = new HashMap<String, Class<?>>(101);
	private static final char CLASS_POINT = '.';
	private static final String PRE_PACKAGE_NAME = "java.lang.";

	@Override
	public Class<?> classForName(String className, @SuppressWarnings("rawtypes") Map context)
			throws ClassNotFoundException {
		Class<?> result = null;
		if (classes.containsKey(className)) {
			result = classes.get(className);
		} else {
			try {
				result = ResourceUtil.classForName(className);
			} catch (ClassNotFoundException e) {
				if (className.indexOf(CLASS_POINT) == -1) {
					result = ResourceUtil.classForName(PRE_PACKAGE_NAME + className);
				} else {
					throw e;
				}
			}
			if (null != result) {
				classes.put(className, result);
			}
		}
		return result;
	}

}
